package xiaoa.java.utils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;

/**
 * ExceptionUtils
 * @author lkc
 * @date 2017年4月27日 上午9:56:08
 * @version V1.0
 *
 */
public class ExceptionUtils {
	
	
	/**
	 * 将错误信息拼接为字符串
	 * @Title: exceptionToString
	 * @param e
	 * @return
	 * @author lkc
	 */
	public static String exceptionToString(Throwable  e){
		
		if (e == null){
			return null;
		}
		
    	Map<String, List<String>>  exceMap = new LinkedHashMap<String, List<String>>();
    	
		// 拼接最上层错误信息
		List<String>  topList = new ArrayList<String>();
		exceMap.put("Exception : " + e + "]" , topList);
		StackTraceElement[] ste = e.getStackTrace();
		for (int k = 0; k < ste.length; k++) {
			topList.add("at "+ ste[k].toString());
		}
		
		// 拼接原因
		Throwable cause = e;
		while ( ( cause = cause.getCause() ) != null){
			
			List<String>  causeList = new ArrayList<String>();
			exceMap.put("cause by : " + cause , causeList);
			StackTraceElement[] st = cause.getStackTrace();
			for (int k = 0; k < st.length; k++) {
				causeList.add(" at " + st[k].toString());
			}
		}
		
		// 将错误信息转为json
		String json = JSON.toJSONString(exceMap);
		
		return json;
	}
	

}
